package info.fastpace.utils.iterator;

import java.util.Iterator;
import java.util.NoSuchElementException;

public abstract class FilterIterator<E> implements Iterator<E> {
	private final Iterator<? extends E> iterator;
	private E next;
	
	
	public FilterIterator(Iterator<? extends E> iterator) {
		this.iterator = iterator;
	}
	
	@Override
	public boolean hasNext() {
		if (next != null) {
			return true;
		}
		
		while (iterator.hasNext()) {
			next = iterator.next();
			if (isAccepted(next)) {
				return true;
			}
		}
		next = null;

		return false;
	}

	protected abstract boolean isAccepted(E e);

	@Override
	public E next() {
		if (!hasNext()) {
			throw new NoSuchElementException("No more elements");
		}
		
		E next = this.next;
		this.next = null;
		
		return next;
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException("Remove method not supported");
	}

}
